package main

import (
	"fmt"
	"net/http"
	"os"
	"regexp"
	"strconv"
	"strings"
)

func main() {
	var startPage, endPage int
	fmt.Printf(" 请输入起始页(>=1) : ")
	fmt.Scan(&startPage)
	fmt.Printf(" 请输入终止页(>=起始页) : ")
	fmt.Scan(&endPage)

	DoPageWork(startPage, endPage)

}

/**
	定义一个函数，爬主页面
**/
func DoPageWork(startPage, endPage int) {
	fmt.Printf(" 准备爬取第【%d】页到【%d】页的网址\n", startPage, endPage)
	page := make(chan int)
	for i := startPage; i <= endPage; i++ {
		go SpiderPape(i, page)
	}
	for i := startPage; i <= endPage; i++ {
		fmt.Printf("\t 第%d个页面爬取完成\n", <-page)
	}
}

/**
	1 eg : https://www.pengfu.com/xiaohua_1.html
	2 正则匹配
		详情链接 : `<h1 class="dp-b"><a href="(?s:(.*?))"`
**/
func SpiderPape(i int, page chan int) {
	url := "https://www.pengfu.com/index_" + strconv.Itoa(i) + ".html"
	fmt.Printf(" 正在爬取第【%d】个网页：%s\n", i, url)

	response, resErr := HttpGetData(url)
	if resErr != nil {
		fmt.Println("page--HttpGetData -- err : ", resErr)
		return
	}
	fmt.Println(" page-result-size :  ", len(response))
	regexUrl := regexp.MustCompile(`<h1 class="dp-b"><a href="(?s:(.*?))"`)
	if regexUrl == nil {
		fmt.Println(" url--regexp.MustCompile err !")
		return
	}

	joyUrlArray := regexUrl.FindAllStringSubmatch(response, -1)

	fileTitle := make([]string, 0)
	fileContent := make([]string, 0)

	for _, data := range joyUrlArray {
		fmt.Println(" detail--url : ", data[1])
		title, content, err := SpiderOneJoke(data[1])
		if err != nil {
			fmt.Println(" spiderOneJoke err , ", err)
			continue
		}
		fileTitle = append(fileTitle, title)
		fileContent = append(fileContent, content)
	}
	StoreJokeToFile(i, fileTitle, fileContent)
	page <- i //写内容，channel-i
}

func StoreJokeToFile(i int, fileTitle, fileContent []string) {
	file, err := os.Create("joke_" + strconv.Itoa(i) + ".txt")
	if err != nil {
		fmt.Println(" os.create err = ", err)
		return
	}
	defer file.Close()

	size := len(fileTitle)
	for j := 0; j < size; j++ {
		file.WriteString("title : " + fileTitle[j] + "\n")
		tmpContent := fileContent[j]
		contentSize := len(tmpContent)
		const lengthMax = 90
		if contentSize < lengthMax {
			file.WriteString("content : " + tmpContent + "\n")
		} else {
			tempContent := tmpContent[0:lengthMax]
			file.WriteString("content : " + tempContent + "\n")
			tempContent = tmpContent[lengthMax-1:]
			file.WriteString("==>" + tempContent + "\n")
		}
		file.WriteString("&&&&&&&&&&& \n")
	}

}

/**
	2 正则匹配
		标题 :	`<h1>(?s:(.*?))</h1>`
			eg :
		内容 : `<h1 class="dp-b"><a href="(?s:(.*?))"`
			eg : <div class="content-txt pt10"> ${内容} </div>
			better : `<div class="content-txt pt10">(?s:(.*?))<a id="prev" href="`
**/
func SpiderOneJoke(url string) (title, content string, err error) {

	response, resErr := HttpGetData(url)
	if resErr != nil {
		fmt.Println(" detail--HttpGetData -- err : ", resErr)
		err = resErr
		return
	}
	regexText := regexp.MustCompile(`<h1>(?s:(.*?))</h1>`)
	if regexText == nil {
		fmt.Println(" detail[title]--regexp.MustCompile err !")
		return
	}

	tempTitle := regexText.FindAllStringSubmatch(response, -1)
	for _, data := range tempTitle {
		title = strings.Replace(data[1], "\t", "", -1)
		break
	}

	regexText = regexp.MustCompile(`<div class="content-txt pt10">(?s:(.*?))<a id="prev" href="`)
	if regexText == nil {
		fmt.Println(" detail{content}--regexp.MustCompile err !")
		return
	}
	tempContent := regexText.FindAllStringSubmatch(response, -1)
	for _, data := range tempContent {
		content = data[1]
		content = strings.Replace(content, "\t", "", -1)
		content = strings.Replace(content, "\r", "", -1)
		content = strings.Replace(content, "\n", "", -1)
		content = strings.Replace(content, "<br/>", "", -1)
		break
	}
	return
}

func HttpGetData(url string) (result string, err error) {
	response, resErr := http.Get(url)
	if resErr != nil {
		err = resErr
		return
	}
	defer response.Body.Close()
	buffer := make([]byte, 4*1024)
	for {
		resIndex, _ := response.Body.Read(buffer)
		if resIndex == 0 {
			fmt.Println("  内容已读取完毕 \n ")
			break
		}
		result += string(buffer[:resIndex])
	}
	return
}
